import { AdminUser } from "@/types/admin/auth";
import { model, Schema, Types } from "mongoose";
import bcrypt from "bcrypt";

const AdminUserSchema = new Schema<AdminUser>(
    {
        username: { type: String, required: true },
        email: { type: String, required: true },
        roles: { type: [Types.ObjectId], default: [] },
        status: { type: Boolean, default: true },
        password: { type: String, required: true },
        nickname: String,
        avatar: String,
        remark: String,
    },
    { timestamps: { createdAt: true, updatedAt: true } }
);

// 创建用户时：把密码字段加密再存进去
AdminUserSchema.pre("save", async function (next) {
    const user = this;
    if (user.isModified("password")) user.password = await bcrypt.hash(user.password, 10); // 加密级别：10-12
    next();
});

// 更新用户信息时：如果更新密码且密码不是哈希格式则加密密码再更新密码，否则直接更新密码
AdminUserSchema.pre("updateOne", async function (next) {
    const update = this.getUpdate() as AdminUser;
    if (update?.password) {
        const isHashed = /^\$2[ayb]\$.{56}$/.test(update.password);
        if (!isHashed) {
            update.password = await bcrypt.hash(update.password, 10);
        }
    }
    next();
});

export const AdminUserModel = model("AdminUser", AdminUserSchema);
